﻿package mortal.game.control
{
    import Engine.RMI.*;
    import Framework.Util.*;
    import Message.Game.*;
    import Message.Login.*;
    import com.gengine.core.*;
    import com.gengine.debug.*;
    import com.gengine.game.*;
    import com.gengine.global.*;
    import com.gengine.resource.*;
    import com.gengine.utils.*;
    import com.greensock.plugins.*;
    import extend.language.*;
    import extend.php.*;
    import flash.display.*;
    import flash.events.*;
    import flash.net.*;
    import flash.system.*;
    import flash.text.*;
    import flash.utils.*;
    import frEngine.util.*;
    import mortal.*;
    import mortal.common.*;
    import mortal.common.global.*;
    import mortal.common.preLoadPage.*;
    import mortal.common.shortcutsKey.*;
    import mortal.game.*;
    import mortal.game.cache.*;
    import mortal.game.events.*;
    import mortal.game.manager.*;
    import mortal.game.mvc.*;
    import mortal.game.net.rmi.*;
    import mortal.game.resource.*;
    import mortal.game.scene3D.map3D.util.*;
    import mortal.game.scene3D.model.*;
    import mortal.game.view.closedBetaGiftBag.*;
    import mortal.game.view.common.guide.*;
    import mortal.game.view.submitBug.*;
    import mortal.game.view.systemHistory.*;
    import mortal.mvc.core.*;

    public class LoginController extends Controller
    {
        public var stage:DisplayObjectContainer;
        private var _sloginGameReturn:SLoginGameReturn;
        private var _mapID:int = 100101;
        private var _currentGridX:int = 200;
        private var _currentGridY:int = 200;
        private var _proxyID:int = 0;
        private var _serverID:int = 0;
        private var roleSelectPage:SelectRoleView;
        private static var _instance:LoginController;

        public function LoginController()
        {
            if (_instance)
            {
                throw new Error("LoginController 单例！");
            }
            return;
        }// end function

        public function loadGame() : void
        {
            Log.debug("flashPlayer version:" + Capabilities.version);
            Log.debug(PreLoginProxy.instance.gameSession.gmaeSession.url, "系统总内存:", System.totalMemory);
            var _loc_1:* = PreLoginProxy.instance.sloginReturn;
            GameRMI.instance.rmiSession = PreLoginProxy.instance.gameSession.gmaeSession;
            RMIConnection.connetIPPort = PreLoginProxy.instance.gameSession.gmaeSession.url;
            GameRMI.instance.loginGameProxy.loginGame_async(new AMI_ILoginGame_loginGame(this.loginGameSuccess, this.loginGameException), _loc_1.playerId, ParamsConst.instance.username, _loc_1.name, _loc_1.sessionKey.id, _loc_1.sessionKey.key, ParamsConst.Version, ParamsConst.instance.currentCity, ParamsConst.instance.isMiniCliet);
            Cache.instance.login.loginData = PreLoginProxy.instance.slogin;
            Cache.instance.login.loginReturn = _loc_1;
            return;
        }// end function

        private function loginGameSuccess(param1:Object, param2:SLoginGameReturn) : void
        {
            var _loc_3:String = null;
            Log.debug(PreLoginProxy.instance.gameSession.gmaeSession.url, "成功", "系统总内存:", System.totalMemory);
            PHPSender.sendGift(param2.player.playerId);
            if (PHPSender.isCreateRole)
            {
                _loc_3 = ParamsConst.instance.gameMsgURL;
                if (_loc_3 != null && _loc_3 != "")
                {
                    sendToURL(new URLRequest(_loc_3 + "&username=" + encodeURI(ParamsConst.instance.username) + "&rolename=" + encodeURI(param2.player.name)));
                }
                PHPSender.sendToURLByPHP(SenderType.LoginGameSuccess);
            }
            PHPSender.isCreateRole = false;
            ClockManager.instance.roleCreateDate = param2.player.createDt;
            ClockManager.instance.setNowTimer(param2.sysDt);
            ClockManager.instance.serverOpenDate = param2.openDt;
            this._sloginGameReturn = param2;
            Cache.instance.login.loginGame = param2;
            this._mapID = this._sloginGameReturn.pos.map;
            this._currentGridX = this._sloginGameReturn.pos.x;
            this._currentGridY = this._sloginGameReturn.pos.y;
            this.initApp();
            GameManager.instance.init();
            ResManager.instance.loadLevelRes();
            PerformanceUtil.instance.start();
            AutoGuideRedPoint.instance.register();
            ClosedBetaGiftBagIcon.instance.show();
            if (Global.isDebugModle)
            {
                cache.interfaceCall.addEvents();
            }
            Dispatcher.dispatchEvent(new DataEvent(EventName.LoginGameSuccess));
            if (ParamsConst.instance.timerTestType > 0)
            {
                setTimeout(this.startTimerTest, 1000 * 10);
                Log.debug("TimerTest start:" + ParamsConst.instance.timerTestType);
            }
            return;
        }// end function

        private function startTimerTest() : void
        {
            var _loc_1:* = new TimerTest(Global.stage);
            _loc_1.addEventListener(Event.CLOSE, this.onTestClose);
            TimerTest.Delay = ParamsConst.instance.timerTestType;
            _loc_1.start();
            return;
        }// end function

        private function onTestClose(event:Event) : void
        {
            GameRMI.instance.close();
            return;
        }// end function

        private function initApp() : void
        {
            this.initConfig();
            GameThreadManager.instance.init();
            TweenPlugin.activate([DynamicPropsPlugin]);
            TweenPlugin.activate([PhysicsPropsPlugin]);
            this.initUI();
            this.initModules();
            this.initMap();
            GameState.isLoginInCompl = true;
            if (GameState.isGameLoadCompl)
            {
                GameLoadBar.instance.hide();
            }
            return;
        }// end function

        private function initConfig() : void
        {
            Log.system("准备初始化屏蔽字", "系统总内存:", System.totalMemory, "时间：", getTimer());
            FilterText.instance.setFilterStr(ConfigManager.instance.getStringByFileName("filterChat.txt"));
            Log.system("初始化屏蔽字完成", "系统总内存:", System.totalMemory, "时间：", getTimer());
            return;
        }// end function

        private function initUI() : void
        {
            Log.system("准备初始化UI", "系统总内存:", System.totalMemory);
            SysHistroyBtn.instance.show();
            GameController.shortcut.view.show();
            GameController.chat.view.show();
            GameController.navbar.view.show();
            GameController.mapNavBar.view.show();
            GameController.avatar.view.show();
            GameController.selectAvatar.view.show();
            GameController.team.view.show();
            GameController.task.view.show();
            SubmitBugIcon.instance.show();
            MsgManager.addSpeakerStage(LayerManager.topLayer);
            GameLayout.instance.init();
            Log.system("初始化UI", "系统总内存:", System.totalMemory);
            return;
        }// end function

        private function initModules() : void
        {
            ModuleConfig.instance.init();
            return;
        }// end function

        private function initMap() : void
        {
            MapConfig.mapPath = PathConst.mapPath;
            MapConfig.modelPath = PathConst.modelPath;
            MapFileUtil.mapID = this._mapID;
            MapFileUtil.proxyID = this._proxyID;
            MapFileUtil.serverID = this._serverID;
            Game.scene.start();
            SceneGlobalPlayer.initGlobalPlayers();
            GameMapUtil.curMapState.initMapId(this._mapID);
            Game.scene.setPlayerPoint(this._mapID, this._currentGridX, this._currentGridY);
            Dispatcher.dispatchEvent(new DataEvent(EventName.ChangeScene));
            Log.debug("地图ID:" + this._mapID);
            GameLayout.instance.resize(true);
            MapFrameUtil.startMapId(this._mapID);
            return;
        }// end function

        public function loginGameException(param1:Exception) : void
        {
            this.showErrorInfo(param1);
            Log.debug(PreLoginProxy.instance.gameSession.gmaeSession.url, "失败");
            PHPSender.sendToURLByPHP(SenderType.LoginGameFail, param1.code + param1.message);
            return;
        }// end function

        private function showErrorInfo(param1:Exception) : void
        {
            var _loc_2:* = new TextField();
            _loc_2.autoSize = TextFieldAutoSize.LEFT;
            _loc_2.textColor = 16777215;
            _loc_2.background = true;
            _loc_2.backgroundColor = 0;
            _loc_2.x = Global.stage.stageWidth / 2 - 100;
            _loc_2.y = Global.stage.stageHeight / 2 - 40;
            if (Global.isDebugModle)
            {
                _loc_2.text = Language.getStringByParam(20413, param1.code, param1.message);
                Global.stage.addChild(_loc_2);
            }
            else
            {
                _loc_2.text = Language.getStringByParam(20414, param1.code);
                Global.stage.addChild(_loc_2);
            }
            return;
        }// end function

        private function onResourceLoaded(event:DataEvent) : void
        {
            if (GameLoadBar.instance)
            {
                GameLoadBar.instance.visible = false;
            }
            return;
        }// end function

        public function showRoleSelectPage() : void
        {
            if (!this.roleSelectPage)
            {
                this.roleSelectPage = new SelectRoleView();
                this.roleSelectPage.addEventListener(EventName.HefuEnterGame, this.onEnterGame);
                this.roleSelectPage.addEventListener(EventName.HefuSetMain, this.onSetMain);
            }
            Global.stage.addChild(this.roleSelectPage);
            GameLoadBar.instance.visible = false;
            return;
        }// end function

        public function hideRoleSelectPage() : void
        {
            if (this.roleSelectPage && this.roleSelectPage.parent)
            {
                this.roleSelectPage.parent.removeChild(this.roleSelectPage);
            }
            GameLoadBar.instance.visible = true;
            return;
        }// end function

        private function onEnterGame(event:DataEvent) : void
        {
            PreLoginProxy.instance.doEnterGame(event.data as SMyRole);
            return;
        }// end function

        private function onSetMain(event:DataEvent) : void
        {
            PreLoginProxy.instance.doSetMain(event.data as SMyRole);
            return;
        }// end function

        public static function get instance() : LoginController
        {
            if (!_instance)
            {
                _instance = new LoginController;
            }
            return _instance;
        }// end function

    }
}
